package com.jshoperxms.controller.api.langdu;

import com.jshoperxms.Response;
import com.jshoperxms.components.wechat.wxcode.WxacodeunlimitController;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.MemberT;
import com.jshoperxms.entity.YdArticleRecordRdT;
import com.jshoperxms.entity.YdRecordRdT;
import com.jshoperxms.entity.YdStatusInfoT;
import com.jshoperxms.service.MemberTService;
import com.jshoperxms.service.YdArticleRecordRdTService;
import com.jshoperxms.service.YdRecordRdTService;
import com.jshoperxms.service.YdStatusInfoTSerivce;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 2018/11/20.
 * Des:小队发布图文朗读内容
 */
@RestController
@RequestMapping("/api/team/artrecord")
public class YdArticleRecordRdTController extends BaseTController {

    @Resource
    private WxacodeunlimitController wxacodeunlimitController;

    @Resource
    private YdRecordRdTService ydRecordRdTService;

    @Resource
    private RecordController recordController;
    @Resource
    private YdArticleRecordRdTService ydArticleRecordRdTService;

    @Resource
    private YdTeamController ydTeamController;

    @Resource
    private MemberTService memberTService;

    @Resource
    private YdStatusInfoTSerivce ydStatusInfoTSerivce;



//    @RequestMapping(value="/updateArtFollowReadingCount",method= RequestMethod.POST)
//    public ResponseEntity updateArtFollowReadingCount(){
//        Map<String,Object> responsedata=new HashMap<>();
//        List<YdArticleRecordRdT>ydArticleRecordRdTS=this.ydArticleRecordRdTService.findAll(YdArticleRecordRdT.class);
//        for(YdArticleRecordRdT yd:ydArticleRecordRdTS){
//            Criterion criterion=Restrictions.eq("followuprdid",yd.getId());
//            int count=this.ydRecordRdTService.count(YdRecordRdT.class,criterion).intValue();
//            System.out.println("count=="+count);
//            if(count!=0){
//                yd.setGfollowreadingcount(count);
//                this.ydArticleRecordRdTService.update(yd);
//            }
//
//        }
//        return Response.success(responsedata);
//
//    }

//    /**
//     * 保存图文音频记录草稿
//     * @param rq
//     * @return
//     */
//    @RequestMapping(value="/saveDraftArtRecord",method= RequestMethod.POST)
//    public ResponseEntity saveDraftArtRecord(@RequestBody YdArticleRecordRdT rq){
//        Map<String,Object> responsedata=new HashMap<>();
//        YdArticleRecordRdT bean=new YdArticleRecordRdT();
//        bean.setId(PrimaryKey.get().toString());
//        bean.setFileurl(rq.getFileurl());
//        bean.setStatus(BaseEnums.DataUsingState.USING.getState());
//        bean.setCreatetime(DateTools.getSystemTimeLong());
//        bean.setCreatorid("0");
//        bean.setUpdatetime(DateTools.getSystemTimeLong());
//        bean.setVersiont(1);
//        bean.setFiletype(rq.getFiletype());
//        bean.setDuration(rq.getDuration());
//        bean.setGbiaoyang(0);
//        bean.setGleafs(10);
//        bean.setGscore(90);
//        bean.setGruntimecount(0);
//        bean.setGsharecount(0);
//        bean.setFileimgs(rq.getFileimgs());
//        bean.setArticlecontent(rq.getArticlecontent());
//        bean.setAuthornick(rq.getAuthornick());
//        bean.setAuthorheadimg(rq.getAuthorheadimg());
//        bean.setWxopenid(rq.getWxopenid());
//        bean.setCurrentpublishcount(rq.getCurrentpublishcount());
//        bean.setTitle(rq.getTitle());
//        bean.setDefaultduration("00:00");
//        bean.setIspublic("0");//默认不公开到朗读乐园
//        bean.setGcomment(0);
//        bean.setTeamcategory(StaticKey.EMPTY);
//        bean.setTeamcategoryid("0");
//        bean.setRecommend("0");//不推荐
//        bean.setDraft("1");//草稿
//        this.ydArticleRecordRdTService.save(bean);
//        recordController.updateYdStatusLangdu(bean.getWxopenid());
//        responsedata.put(TagWords.SUCCESS,true);
//        responsedata.put("artrecordid",bean.getId());
//        return Response.success(responsedata);
//    }

    /**
     * 保存并预览图文音频内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/saveArtRecordTo",method= RequestMethod.POST)
    public ResponseEntity saveArtRecordTo(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
            YdArticleRecordRdT bean=this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class,rq.getId());
            if(bean!=null){
                //通过已经有的草稿记录更细数据
                bean.setFileurl(rq.getFileurl());
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(bean.getVersiont()+1);
                bean.setFiletype(rq.getFiletype());
                bean.setDuration(rq.getDuration());
                bean.setFileimgs(rq.getFileimgs());
                bean.setArticlecontent(rq.getArticlecontent());
                bean.setAuthornick(rq.getAuthornick());
                bean.setAuthorheadimg(rq.getAuthorheadimg());
                bean.setWxopenid(rq.getWxopenid());
                bean.setTitle(rq.getTitle());
                bean.setTeamcategory(rq.getTeamcategory());
                bean.setTeamcategoryid(rq.getTeamcategoryid());
                bean.setDraft("1");//草稿表示正式发布
                bean.setFromby(rq.getAuthornick());
                bean.setTeamid(rq.getTeamid());
                this.ydArticleRecordRdTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put("artrecordid",bean.getId());
            }else {
                Criterion criterion=Restrictions.eq("wxopenid",rq.getWxopenid());
                MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion);
                if(memberT!=null){
                    bean = new YdArticleRecordRdT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setFileurl(rq.getFileurl());
                    bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                    bean.setCreatetime(DateTools.getSystemTimeLong());
                    bean.setCreatorid("0");
                    bean.setUpdatetime(DateTools.getSystemTimeLong());
                    bean.setVersiont(1);
                    bean.setFiletype(rq.getFiletype());
                    bean.setDuration(rq.getDuration());
                    bean.setGbiaoyang(0);
                    bean.setGleafs(50);
                    bean.setGscore(90);
                    bean.setGruntimecount(1);
                    bean.setGsharecount(0);
                    bean.setFileimgs(rq.getFileimgs());
                    bean.setArticlecontent(rq.getArticlecontent());
                    bean.setAuthornick(rq.getAuthornick());
                    bean.setAuthorheadimg(rq.getAuthorheadimg());
                    bean.setWxopenid(rq.getWxopenid());
                    bean.setCurrentpublishcount(rq.getCurrentpublishcount());
                    bean.setTitle(rq.getTitle());
                    bean.setDefaultduration("00:00");
                    bean.setIspublic("0");//默认不公开到朗读乐园
                    bean.setGcomment(0);
                    bean.setTeamcategory(rq.getTeamcategory());
                    bean.setTeamcategoryid(rq.getTeamcategoryid());
                    bean.setRecommend("0");//不推荐
                    bean.setDraft("1");
                    bean.setSubcategory(rq.getSubcategory());
                    bean.setSubcategoryid(rq.getSubcategoryid());
                    bean.setFromby(rq.getAuthornick());
                    bean.setTeamid(rq.getTeamid());
                    bean.setMemberid(memberT.getId());
                    this.ydArticleRecordRdTService.save(bean);
                    responsedata.put(TagWords.SUCCESS, true);
                    responsedata.put("artrecordid", bean.getId());
                    this.ydTeamController.updateTeamContentCount(bean.getTeamid());
                    this.updateYdLeafs(bean.getWxopenid());
                }else{
                    responsedata.put(TagWords.SUCCESS, false);
                    responsedata.put(TagWords.MSG, WarnWrods.EMPTY_RECORD);
                }

            }
        return Response.success(responsedata);

    }

    /**
     * 更新朗读树叶
     * @param wxopenid
     */
    public void updateYdLeafs(String wxopenid){
        Criterion criterion=Restrictions.eq("wxopenid",wxopenid);
        YdStatusInfoT bean=this.ydStatusInfoTSerivce.findOneByCriteria(YdStatusInfoT.class,criterion);
        if(bean!=null){
            bean.setTotalyuedu(bean.getTotalyuedu()+1);
            bean.setTotalleafs(bean.getTotalleafs()+20);
            this.ydStatusInfoTSerivce.update(bean);
        }
    }





    /**
     * 只更新图文，不更新音频内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/updateArtRecordOnlyContent",method= RequestMethod.POST)
    public ResponseEntity updateArtRecordOnlyContent(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        YdArticleRecordRdT bean=this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class,rq.getId());
        if(bean!=null){
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(bean.getVersiont()+1);
            bean.setFileimgs(rq.getFileimgs());
            bean.setArticlecontent(rq.getArticlecontent());
            bean.setAuthornick(rq.getAuthornick());
            bean.setAuthorheadimg(rq.getAuthorheadimg());
            bean.setTitle(rq.getTitle());
            this.ydArticleRecordRdTService.update(bean);
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put("artrecordid",bean.getId());
        }
        return Response.success(responsedata);

    }



    /**
     * 发布内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/publishArtRecord",method= RequestMethod.POST)
    public ResponseEntity publishArtRecord(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())) {
            YdArticleRecordRdT bean = this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class, rq.getId());
            if (bean != null) {
                bean.setDraft("0");//0表示不是草稿了，正式发布了
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(bean.getVersiont()+1);
                this.ydArticleRecordRdTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put("artrecordid",bean.getId());

            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);

        }
        return Response.success(responsedata);

    }




    /**
     * 查询图文朗读内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/findArtRecord",method= RequestMethod.POST)
    public ResponseEntity findArtRecord(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())) {
            YdArticleRecordRdT bean = this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class, rq.getId());
            if (bean != null) {
                responsedata.put("publishtime",DateTools.formateLongDateToString(bean.getCreatetime()));
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.BEAN,bean);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);

        }
        return Response.success(responsedata);
    }

    /**
     * 获取图文朗读跟读的列表
     * @param rq
     * @return
     */
    @RequestMapping(value="/findFollowArtRecords",method= RequestMethod.POST)
    public ResponseEntity findFollowArtRecords(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        Criterion criterion=Restrictions.and(Restrictions.eq("followuprdid",rq.getId())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
        List<YdRecordRdT>list=this.ydRecordRdTService.findByCriteriaByPage(YdRecordRdT.class,criterion,Order.desc("gbiaoyang"),1,100);
        responsedata.put("results",list);
        responsedata.put(TagWords.SUCCESS,true);
        return Response.success(responsedata);
    }


    /**
     * 我的图文朗读记录
     * @param rq
     * @return
     */
    @RequestMapping(value="/findMineYdArticleRecords",method= RequestMethod.POST)
    public ResponseEntity findMineYdArticleRecordsList(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        Criterion criterion= Restrictions.and(Restrictions.eq("wxopenid",rq.getWxopenid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
        int currentPage=rq.getStart();
        int lineSize=rq.getLength();
        int records=this.ydArticleRecordRdTService.count(YdArticleRecordRdT.class,criterion).intValue();
        List<YdArticleRecordRdT> list=this.ydArticleRecordRdTService.findByCriteriaByPage(YdArticleRecordRdT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
        rq.setRecordsTotal(records);
        responsedata.put("results",list);
        responsedata.put("start",rq.getNextPageNo());
        responsedata.put("totalPage",rq.getTotalPage());
        responsedata.put("totalrecords",records);
        responsedata.put(TagWords.SUCCESS,true);
        return Response.success(responsedata);
    }


    /**
     * 更新图文朗读分享次数
     * @param rq
     * @return
     */
    @RequestMapping(value="/updateYdArticleRecordsShares",method= RequestMethod.POST)
    public ResponseEntity updateYdArticleRecordsShares(@RequestBody YdArticleRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())) {
            YdArticleRecordRdT bean = this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class, rq.getId());
            if (bean != null) {
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setGsharecount(bean.getGsharecount() + 1);
                bean.setVersiont(bean.getVersiont() + 1);
                this.ydArticleRecordRdTService.update(bean);
                recordController.updateTotalShares(bean.getWxopenid());
                ydTeamController.updateTeamContentSharesCount(bean.getTeamid());
            }
        }else {
            responsedata.put(TagWords.SUCCESS, false);
        }
        return Response.success(responsedata);
    }


    /**
     * 更新图文朗读表扬数量
     * @param rq
     * @return
     */
    @RequestMapping(value="/updateYdArticleBiaoyang",method= RequestMethod.POST)
    public ResponseEntity updateYdBiaoyang(@RequestBody YdRecordRdT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            YdArticleRecordRdT bean=this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class,rq.getId());
            if(bean!=null){
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setGbiaoyang(bean.getGbiaoyang()+1);
                bean.setVersiont(bean.getVersiont()+1);
                this.ydArticleRecordRdTService.update(bean);
                recordController.updateYdStatus(bean.getWxopenid());
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }


    /**
     * 根据图文id 查询朗读的内容列表
     * @param rq
     * @return
     */
    @RequestMapping(value="/findRecordsByYdArticle",method= RequestMethod.POST)
    public ResponseEntity findRecordsByYdArticle(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getArtrecordid())){
            int currentPage=rq.getStart();
            int lineSize=rq.getLength();
            Criterion criterion=Restrictions.and(Restrictions.eq("followuprdid",rq.getArtrecordid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            int records=this.ydRecordRdTService.count(YdRecordRdT.class,criterion).intValue();
            List<YdRecordRdT> list=this.ydRecordRdTService.findByCriteriaByPage(YdRecordRdT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(records);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
            return Response.success(responsedata);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 搜索文章
     * @param rq
     * @return
     */
    @RequestMapping(value="/searchYdArtRecords",method= RequestMethod.POST)
    public ResponseEntity searchYdArtRecords(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTitle())){
            Criterion criterion=Restrictions.and(Restrictions.like("title",rq.getTitle(), MatchMode.ANYWHERE)).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            List<YdArticleRecordRdT>list=this.ydArticleRecordRdTService.findByCriteriaByPage(YdArticleRecordRdT.class,criterion,Order.desc(TagWords.CREATETIME),1,50);
            responsedata.put("results",list);
            responsedata.put(TagWords.SUCCESS,true);
            return Response.success(responsedata);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }




    /**
     * 生成音频朗读小程序二维码
     * @param rq
     * @return
     */
    @RequestMapping(value="/createYdTeamArtrecordWxCode",method= RequestMethod.POST)
    public ResponseEntity createYdrecordWxCode(HttpServletRequest request, @RequestBody YdRecordRdT rq) throws IOException {
        Map<String, Object> responsedata = new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            String senceparams=rq.getId();
            responsedata=wxacodeunlimitController.createYdTeamArtRecordWxCode(request,senceparams);
            if(responsedata.get("wxcodeurl")!=null){
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }

}
